/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.shop.web.controllers;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;
import org.shop.domain.Customer;
import org.shop.domain.Inventory;
import org.shop.domain.Purchase;
import org.shop.domain.SoldItemDescription;
import org.shop.domain.Store;
import org.shop.domain.Transactions;
import org.shop.service.InventoryService;
import org.shop.utils.InstanceUtils;
import org.shop.web.utils.RootController;

/**
 *
 * @author vinod
 */
public class CustomerBillingController extends RootController {

    private static final Logger log = Logger.getLogger(CustomerBillingController.class);

    @Override
    protected void doWork(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        InstanceUtils utils = new InstanceUtils();
        InventoryService service = utils.getService();
        String customerName = request.getParameter("custName").trim();
        Customer customer = service.findCustomerByName(customerName);
        if (customer == null) {
            request.setAttribute("errorMsg", "Invalid Customer Name! Please Enter valid Username");
            request.getRequestDispatcher("/customerBilling.jsp").forward(request, response);
        } else {
            String[] itemIds = request.getParameterValues("itemId");
            String[] itemNames = request.getParameterValues("itemName");
            String[] noItems = request.getParameterValues("noItems");
            String[] itemCosts = request.getParameterValues("itemCost");
            String[] ItemsPrice = request.getParameterValues("ItemsPrice");
            double totalPrice = Double.valueOf(request.getParameter("totalPrice").trim());
            double paidAmount = Double.valueOf(request.getParameter("paidAmount").trim());

            Inventory inventory = service.getInventory(customer.getCustomer_Id());
            List<SoldItemDescription> list = new ArrayList<SoldItemDescription>();
            Purchase purchase = inventory.getBill_Id();
            log.info("Purchase Object" + purchase);

            if (purchase == null) {
                purchase = utils.getPurchase();
                purchase.setCustomer_Id(customer);
                purchase.setPurchase_Date(new Date());
                purchase.setTotalSum(totalPrice);
                inventory.setBill_Id(purchase);
                log.warn("Inventory Object:-" + inventory);
                service.updateInventoryDetails(inventory);
                log.warn("Purchase Object:-" + purchase.getBill_Id());
                log.info("New Purchase" + purchase);
            }
            Date soldItemsDate = new Date();

            for (int i = 0; i < itemIds.length; i++) {
                if (itemIds[i] != null && itemNames[i] != null && noItems[i] != null && ItemsPrice[i] != null) {
                    SoldItemDescription desc = utils.getItemDesc();
                    String itemId = itemIds[i].trim();
                    String itemName = itemNames[i].trim();
                    int noItem = Integer.valueOf(noItems[i].trim());
                    double itemCost = Double.valueOf(itemCosts[i].trim());
                    double itemsPrice = Double.valueOf(ItemsPrice[i].trim());

                    desc.setCustomer_Id(inventory.getCustomer_Id());
                    log.info("Bill ID loop:- " + inventory.getBill_Id().getBill_Id());
                    desc.setItem_Id(itemId);
                    desc.setQuantity(noItem);
                    desc.setRate(itemCost);
                    desc.setPrice(itemsPrice);
                    desc.setDate(soldItemsDate);
                    list.add(desc);

                    Store store = service.findByItem(itemId, itemName);
                    //int totalItems = store.getTotal_Items();
                    int soldItems = store.getSoldItems();
                    int remainItems = store.getRemainingItems();
                    if (remainItems < noItem) {
                        String msg = store.getItem_Name() + "Not Avaliabled in the Store" + "Avaliabled Items:-" + remainItems;
                        request.setAttribute("Warning", msg);
                        request.getRequestDispatcher("/customerBilling.jsp").forward(request, response);
                        return;
                    }
                    store.setSoldItems(soldItems + noItem);
                    store.setRemainingItems(remainItems - noItem);
                    service.updateStore(store);
                }
            }
            service.addSoldItemDescription(list);
            Transactions transaction = new Transactions();
            log.info("My Information:-" + purchase.getBill_Id());
            transaction.setCustomer_Id(customer);
            transaction.setDate(new Date());
            transaction.setPurchase_Amount(totalPrice);
            transaction.setPayment_Amount(paidAmount);
            transaction.setRemaining_Balance(totalPrice - paidAmount);
            log.warn(transaction);
            service.updateTransactions(transaction);
            log.info("Purchase Object" + purchase);
            response.sendRedirect("createCustomer.jsp");

        }

    }
}
